﻿using System.Collections.Generic;
using EnetaMvc.Core.Domain.News;
using EnetaMvc.Core.Repositories;
using EnetaMvc.Infrastructure;
using NHibernate;
using NHibernate.Criterion;

namespace EnetaMvc.Data.NHibernate.Repositories
{
    public class BlogRepository : BaseRepository, IBlogRepository
    {
        private readonly ISession _session;

        public BlogRepository(IMapperSession session) : base(((NHSession)session).GetCurrentSession())
        {
            _session = ((NHSession)session).GetCurrentSession();
        }

        public IList<Blog> ListBlogs()
        {
            return _session.CreateCriteria<Blog>().List<Blog>();
        }

        public IList<Blog> ListPublishedBlogs()
        {
            var criteria = _session.CreateCriteria<Blog>();
            criteria.CreateCriteria("PublishingState").Add(Expression.Eq("IsVisibleOnPublicSite", true));

            return criteria.List<Blog>();
        }

        public IList<Blog> ListPendingBlogs()
        {
            var criteria = _session.CreateCriteria<Blog>();
            criteria.CreateCriteria("PublishingState").Add(Expression.Eq("Id", 2L));
            criteria.SetMaxResults(20);

            return criteria.List<Blog>();
        }

        public Blog GetBlogById(long id)
        {
            return _session.Get<Blog>(id);
        }

        public void SaveBlog(Blog blog)
        {
            if (blog == null)
                return;

            SaveInTransaction(blog);
        }

        public Blog GetPublishedBlogById(long id)
        {
            var blog = GetBlogById(id);
            if (blog == null)
                return null;

            if (blog.PublishingState == null)
                return null;
            if (!blog.PublishingState.IsVisibleOnPublicSite)
                return null;

            return blog;
        }

        public IList<Blog> ListBlogsForUser(string token)
        {
            var criteria = _session.CreateCriteria<Blog>();
            criteria.CreateCriteria("CreatedBy")
                    .Add(Expression.Eq("LiveIdToken", token));

            return criteria.List<Blog>();
        }
    }
}
